<template>
  <drag-modal
    title="新增"
    :width="400"
    :visible="visible"
    :destroyOnClose="true"
    :confirmLoading="submitLoading"
    :maskClosable="false"
    @ok="ok"
    @cancel="cancel"
  >
    <a-spin :spinning="loading">
      <a-form-model :model="form" ref="form" :rules="validatorRules" :labelCol="{span: 5}" :wrapperCol="{span: 16, offset: 1}">
        <div class="fold">
          <a-form-model-item
            label="标签"
            prop="label"
          >
            <a-input allowClear v-model="form.label" />
          </a-form-model-item>
          <a-form-model-item
            label="值"
            prop="value"
          >
            <a-input allowClear v-model="form.value" />
          </a-form-model-item>
          <a-form-model-item
            label="排序"
            prop="sort"
          >
            <a-input allowClear v-model="form.sort" @change="(e) => form.sort = e.target.value.replace(/[^0-9]/g, '')" />
          </a-form-model-item>
          <a-form-model-item
            label="状态"
            prop="status"
          >
            <a-select v-model="form.status" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
              <a-select-option v-for="item in dict.status" :key="item.key" :value="item.value">{{item.title}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-spin>
  </drag-modal>
</template>

<script>
import {dictService} from '@/services'

export default {
  name: 'AddModal',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      submitLoading: false,
      form: {
        label: undefined,
        value: undefined,
        sort: undefined,
        status: undefined,
        parentId: undefined
      },
      validatorRules: {
        label: [
          { required: true, message: '请输入标签', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入值', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      dict: {
        status: []
      }
    }
  },
  methods: {
    cancel() {
      this.$emit('cancel')
    },
    ok() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          dictService.add(JSON.stringify(this.form)).then(res => {
            const result = res.data
            if (result.code === 200) {
              this.$emit('ok')
              this.$message.success(result.msg)
            }
          }).finally(this.submitLoading = false)
        }
      })
    }
  },
  mounted() {
    this.getDict(JSON.stringify({code: 'SYS_STATUS'})).then(res => this.dict.status = res.data.data)
  }
}
</script>
<style scoped lang="less">
</style>